<?php
namespace App\Service;
use App\Common\Logs\Logs;
use App\Common\Utill\OperationLog;
use App\Models\Admin;
use App\Models\Articles;
use App\Models\Websites;
use App\Models\WebsitesAdmin;
use App\Models\WebsitesDomainRecord;
use App\Models\WebsiteStyle;
use Illuminate\Support\Facades\DB;

class WebsitesService extends CommonService{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 列表数据
     * @param $request
     * @param $num
     * @return array|mixed
     */
    public function getListData($request, $num)
    {
        $model = new Websites();
        $query = $model::query();
        $query->where('is_del',1);
        $accountAuthType = self::accountAuthType();
        if($accountAuthType != 1){
             $masterAccountId = self::masterAccountId();
             $getWebsiteAdminIds = WebsitesAdmin::query()->where('admin_id',$masterAccountId)->pluck('website_id');
             if(!$getWebsiteAdminIds){
                 $query->where('id',0);
             }else{
                 $query->whereIn('id',$getWebsiteAdminIds);
             }
        }
        //标题
        $title = $request->input('title', '');
        if ($title) {
            $query->where('title', 'like', '%' . $title . '%');
        }
        //状态
        $status = $request->input('status', '');
        if ($status) {
            $query->where('status', $status);
        }
        $query->orderBy('id', 'desc');
        $result = $query->paginate($num)->toArray();
        foreach ($result['data'] as $key => $val) {
            $result['data'][$key]['websiteUserName'] = '';
            $result['data'][$key]['statusName'] = $val['status'] == 1 ? '开启' : '关闭';
            if(!$val['image_logo']){
                $result['data'][$key]['image_logo'] = '/uploads/images/inits/no.png';
            }
            $result['data'][$key]['article_count'] = Articles::query()->where('website_id',$val['id'])->where('is_del',1)->count();
            //获取管理员信息
            $websiteAdmin = WebsitesAdmin::query()->where('website_id',$val['id'])->select("id","websites_style_id","admin_id")->first();
            if($websiteAdmin['admin_id']){
                $result['data'][$key]['websiteUserName'] = Admin::query()->where('id',$websiteAdmin['admin_id'])->value('username');
            }
            if($websiteAdmin['websites_style_id']){
                $result['data'][$key]['websiteStyeName'] = WebsiteStyle::query()->where('id',$websiteAdmin['websites_style_id'])->value('names');
            }

        }
        return $this->success('SUCCESS', $result['total'], $result['data']);
    }

    /**
     * 添加保存
     * @param $names
     * @param $domains
     * @param $titles
     * @param $keywords
     * @param $description
     * @param $image_logo
     * @return array|mixed
     */
    public function store($names,$domains,$titles,$keywords,$description,$image_logo,$adminUserId,$emails,$phones,$address,$aboutUs,$websitesStyleId,$copyright_info,$copyright_icp)
    {
        $isConfirm = Websites::query()->where("domains",$domains)->where("status",1)->where("is_del",1)->exists();
        if($isConfirm){
            return $this->error('网址已存在,请换个新的网址');
        }
        $postData['names'] = $names;
        $postData['domains'] = $domains;
        $postData['titles'] = $titles ?? "";
        $postData['keywords'] = $keywords ?? "";
        $postData['description'] = $description ?? "";
        $postData['image_logo'] = $image_logo ?? "";
        $postData['emails'] = $emails ?? "";
        $postData['phones'] = $phones ?? "";
        $postData['address'] = $address ?? "";
        $postData['about_us'] = $aboutUs ?? "";
        $postData['copyright_info'] = $copyright_info ?? "";
        $postData['copyright_icp'] = $copyright_icp ?? "";
        $postData['status'] = 1;
        $postData['created_at'] = date('Y-m-d H:i:s');
        $lastId = Websites::query()->insertGetId($postData);
        if(!$lastId){
            return $this->error('添加失败');
        }
        //关联表
        $adminId = $this->adminId;
        $websiteAdminData['website_id'] = $lastId;
        $websiteAdminData['websites_style_id'] = $websitesStyleId;
        $websiteAdminData['admin_id'] = $adminId;
        if($adminId == 1){
            $websiteAdminData['admin_id'] = $adminUserId;
        }
        $websiteAdminData['created_at'] = date('Y-m-d H:i:s');
        WebsitesAdmin::query()->insert($websiteAdminData);
        //网站域名记录
        $styleName = WebsiteStyle::query()->where('id',$websitesStyleId)->value('names');
        $this->websiteDomainRecord($lastId,$domains,$websitesStyleId,$styleName);
        OperationLog::record(1,'网站管理-添加',$lastId,$postData);
        return $this->success('添加成功');
    }

    /**
     * 网站域名记录
     * @param $websiteId
     * @param $domainName
     * @param $styleId
     * @param $styleName
     * @return void
     */
    public function websiteDomainRecord($websiteId,$domainName,$styleId,$styleName)
    {
        $postData = [];
        $postData['website_id']  = $websiteId;
        $postData['domain_name'] = $domainName;
        $postData['style_id']    = $styleId;
        $postData['style_name']  = $styleName;
        $postData['status'] = 1;
        $postData['created_at'] = date("Y-m-d H:i:s");
        $postIni['domain_name'] = $domainName;
        $preId = WebsitesDomainRecord::query()->where($postIni)->orderBy("id","desc")->value("id") ?? 0;
        $postData['previous_id'] = $preId;
        Logs::info("step-1",$postData);
        WebsitesDomainRecord::query()->insert($postData);
    }

    /**
     * 编辑保存
     * @param $title
     * @param $domains
     * @return array|mixed
     */
    public function update($id,$names,$domains,$titles,$keywords,$description,$image_logo,$adminUserId,$emails,$phones,$address,$aboutUs,$websitesStyleId=0,$copyright_info="",$copyright_icp="")
    {
        $isConfirm = Websites::query()->where('id','<>',$id)->where("domains",$domains)->exists();
        if($isConfirm){
            return $this->error('网址已存在,请换个新的网址');
        }
        $oldData = Websites::query()->where('id',$id)->first()->toArray();
        $postData['names'] = $names;
        $postData['domains'] = $domains;
        $postData['titles'] = $titles;
        $postData['keywords'] = $keywords;
        $postData['description'] = $description;
        $postData['image_logo'] = $image_logo;
        $postData['emails'] = $emails;
        $postData['phones'] = $phones;
        $postData['address'] = $address;
        $postData['about_us'] = $aboutUs;
        $postData['copyright_info'] = $copyright_info;
        $postData['copyright_icp'] = $copyright_icp;
        $postData['updated_at'] = date('Y-m-d H:i:s');
        $result = Websites::query()->where('id', $id)->update($postData);
        if(!$result){
            return $this->error('编辑失败');
        }
        OperationLog::record(2,'网站管理-编辑',$id,$postData,$oldData);
        return $this->success('编辑成功');
    }

    /**
     * 状态修改
     * @return void
     */
    public function status($id)
    {
        $websitesData = Websites::query()->where(['id'=>$id])->select("id","status","domains")->first();
        $isShow = $websitesData['status'];
        $data['status'] = $isShow == 1 ? -1 : 1;
        if($data['status'] == 1){//开启
             $whereIni['domains'] = $websitesData['domains'];
             $whereIni['is_del'] = 1;
             $whereIni['status'] =1;
             $websiteStatus = Websites::query()->where($whereIni)->exists();
             if($websiteStatus){
                 return $this->error('该域名有网站在使用,请换个域名');
             }
        }
        $data['updated_at'] = date('Y-m-d H:i:s');
        $result = Websites::query()->where('id', $id)->update($data);
        if (!$result) {
           return $this->error('设置失败');
        }
        $this->articleStatus($id,$data['status']);
        OperationLog::record(2,'网站管理-状态编辑',$id,['status'=>$data['status']],['status'=>$isShow]);
        return $this->success('设置成功');
    }

    /**
     * 单个删除
     */
    public function delOne($id)
    {
        $result = Websites::findOrFail($id);
        $result->is_del = -1;
        $result->updated_at = date("Y-m-d H:i:s");
        if (!$result->save()) {
            return $this->error('删除失败');
        }
        //
        DB::table("pd_websites_admin")->where('website_id',$id)->delete();
        OperationLog::record(3,'网站管理-删除',$id);
        return $this->success("删除成功");
    }



    /**
     * 网站下面的文章操作
     * @param $id
     * @param $status
     * @return void
     */
    public function articleStatus($id,$status)
    {
        if($status == -1){//下架
            $whereIni['website_id'] = $id;
            $whereIni['status'] = 2;
            $countNumber = Articles::query()->where($whereIni)->count();
            if($countNumber){
                $saveData['status'] = -1;
                $saveData['from_source'] = 3;
                Articles::query()->where($whereIni)->update($saveData);
            }
        }else{//上架
            $onlineIni['website_id'] = $id;
            $onlineIni['from_source'] = 3;
            $countNumber = Articles::query()->where($onlineIni)->count();
            if($countNumber){
                $saveData['status'] = 2;
                $saveData['from_source'] = 4;
                Articles::query()->where($onlineIni)->update($saveData);
            }
        }
    }

    /**
     * 获取网站列表
     * @param $status  //状态 1=开启 2=全部
     * @param $arrType //1=一维数组 2=二维数组
     * @return mixed[]
     */
    public static function getWebsiteData($status = 2,$arrType=2)
    {
        $whereIni['is_del'] = 1;
        if($status == 1){
            $whereIni['status'] = 1;
        }
        $query = Websites::query();
        $accountAuthType = self::accountAuthType();
        if($accountAuthType != 1){
             $admindId = self::masterAccountId();
             $websiteAdmin = WebsitesAdmin::query()->where('admin_id',$admindId)->pluck('website_id')->toArray();
             if(!$websiteAdmin){
                   $query->where('id',0);
             }else{
                   $query->whereIn('id',$websiteAdmin);
             }
        }
        $data = $query->where($whereIni)
            ->select('id','names','domains')
            ->orderBy('id','desc')
            ->get()->toArray();
        if($arrType==1){
            $result =[];
            foreach ($data as $k => $v) {
                $result[$v['id']] = $v['names'];
            }
            return $result;
        }
        return $data;
    }
}
